<template>
	<view class="city_picker">
		<u-picker ref="addrPicker" :show="show" :columns="addrColumnsData" keyName="name" @change="changeAddress"
			@cancel="handleClose" @confirm="handleAddrConfirm">
		</u-picker>
	</view>
</template>

<script>
	import cityCode from '@/static/json/new_file.json'
	export default {
		name: "city_picker",
		data() {
			return {
				addrColumnsData: [],
				show: false,
			};
		},
		props: ['formData'],
		methods: {
			/** 省市区三级联动数据初始化*/
			async init() {
				// 赋初值
				this.addrColumnsData[0] = cityCode.map(item => {
					return {
						name: item.name,
						code: item.code
					}
				})
				this.addrColumnsData[1] = cityCode[0].children.map(item => {
					return {
						name: item.name,
						code: item.code
					}
				})
				this.addrColumnsData[2] = cityCode[0].children[0].children.map(item => {
					return {
						name: item.name,
						code: item.code
					}
				})
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				// const picker = this.$refs.addrPicker
				// picker.setColumns(this.addrColumnsData)
				// console.log("addrColumnsData",this.addrColumnsData)
			},
			/** 省市区三级联动选择地址改变*/
			changeAddress(e) {
				const {
					columnIndex, // 当前列下标
					value, // 为当前变化列的数组内容
					values, // 全部列数组内容
					index, // 当前值下标
					indexs, // 当前地区值下标
					picker = this.$refs.addrPicker, // 微信小程序无法将picker实例传出来，只能通过ref操作
				} = e

				// 第一列改变
				if (columnIndex === 0) {
					// 获取第二列的值
					let items = cityCode[index].children.map(item => {
						return {
							name: item.name,
							code: item.code
						}
					})
					picker.setColumnValues(1, items)

					// 获得第二列初始化后的第三列的值
					items = cityCode[index].children[0].children.map(item => {
						return {
							name: item.name,
							code: item.code
						}
					})
					picker.setColumnValues(2, items)
				}

				// 第二列改变
				if (columnIndex === 1) {
					// 获得第三列的值
					let items = cityCode[indexs[0]].children[index].children.map(item => {
						return {
							name: item.name,
							code: item.code
						}
					})
					picker.setColumnValues(2, items)
				}
			},

			/** 省市区三级联动确认*/
			handleAddrConfirm(e) {
				const {
					indexs,
					values,
					value
				} = e
				this.formData.address = value[0].name + '-' + value[1].name + '-' + value[2].name
				// console.log(this.addr);
				this.show = false

				// console.log("e",e)
				this.formData.province_id = e.value[0].code;
				this.formData.city_id = e.value[1].code;
				this.formData.area_id = e.value[2].code;
			},
			handleClose() {
				this.show = false;
			},
			handleShow() {
				this.show = true;
			},
		},
		created() {
			this.init();
		}
	}
</script>

<style lang="less">

</style>